
package com.wangzha.business.ctrl;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;
import com.wangzha.business.service.DeviceGroupService;
import com.wangzha.business.service.DeviceService;
import com.wangzha.common.base.BaseController;
import com.wangzha.common.cache.CacheKey;
import com.wangzha.common.model.DeviceGroup;
import com.wangzha.common.vo.Grid;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 设备分组
 */
@Path("/device/group")
public class DeviceGroupController extends BaseController {

    @Inject
    DeviceGroupService deviceGroupService;

    @Inject
    DeviceService deviceService;

    public void index(){
        render("index.html");
    }

    public void list() {
        Record record = new Record();
        record.set("user_code", getVisitor().getCode());
        Grid grid = deviceGroupService.queryForListEq(getParaToInt("pageNumber", 1),
                getParaToInt("pageSize", 10), record);
        renderJson(grid);
    }

    public void deviceList() {
        List<Record> deviceList = deviceService.queryByUserCodeAndGroupId(getVisitor().getCode(), getLong("groupId"));
        for (Record record : deviceList) {
            record.set("online", StringUtils.isBlank(Redis.use().get(String.format(CacheKey.DEVICE_HEARTBEAT, record.getStr("activation_code")))) ? "离线" : "在线");
        }
        renderJson(deviceList);
    }

    public void add() {
        render("add.html");
    }

    public void save() {
        DeviceGroup entity = getBean(DeviceGroup.class);
        entity.setUserCode(getVisitor().getCode());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.save();
        setAttr("deviceGroup", entity);
        render("add.html");
    }

    public void edit() {
        setAttr("deviceGroup", deviceGroupService.findById(getPara(0)));
        render("edit.html");
    }

    public void update() {
        DeviceGroup entity = getBean(DeviceGroup.class);
        entity.setUpdateTime(new Date());
        entity.update();
        setAttr("deviceGroup", entity);
        render("edit.html");
    }

    public void delete() {
        deviceGroupService.deleteByIds(getIds());
        renderJson(suc());
    }
}

